package com.itheima.health.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.health.dto.UserDto;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.mapper.UserMapper;
import com.itheima.health.pojo.User;
import com.itheima.health.service.RoleService;
import com.itheima.health.service.User2Service;
import com.itheima.health.vo.UserVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class User2ServiceImpl extends ServiceImpl<UserMapper, User> implements User2Service {

    @Autowired
    private RoleService roleService;

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Page pageData=null;
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        if(queryPageBean.getQueryString()==null){
            pageData=page(new Page<>(queryPageBean.getCurrentPage(),queryPageBean.getPageSize()));
        }else {
            wrapper.like("username",queryPageBean.getQueryString());
            pageData=page(new Page<>(queryPageBean.getCurrentPage(),queryPageBean.getPageSize()),wrapper);
        }

        return new PageResult(pageData.getTotal(),pageData.getRecords());
    }

    @Override
    public boolean saveUpdate(UserDto userDto) {
        Integer uid=userDto.getId();
        if (StringUtils.isNotBlank(String.valueOf(uid))){
            //根据人员id删除  中间表  数据
            baseMapper.deleteRidByUid(uid);
        }
        //将人员信息 存入  人员表格
        boolean flag = saveOrUpdate(userDto);
        uid=userDto.getId();

        //根据人员id在 中间表 中循环录入角色id信息
        Integer[] roleIds = userDto.getRoleIds();
        if (roleIds!=null&&roleIds.length>0){
            for (Integer rid : roleIds) {
                baseMapper.addRidAndUid(uid,rid);
            }
        }

        return false;
    }

    @Override
    public UserVO findByUid(Integer uid) {
        //通过人员Id查询人员信息 人员表
        UserVO userVO=baseMapper.findByUid(uid);
        //查询所有角色信息放到集合中  角色表
        userVO.setRoleList(roleService.list());
        //通过人员id查询所拥有角色数组  中间表
        userVO.setRoleIds(baseMapper.findRids(uid));
        return userVO;
    }

    @Override
    public Boolean deleteById(int id) {
        return baseMapper.deleteById(id)==1;
    }
}
